package com.yuyou.tas.lesson.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.yuyou.tas.lesson.service.IBaseTermService;
import com.yuyou.tas.lesson.service.comm.OrganLimitService;
import com.yuyou.tas.service.api.lesson.dto.DtoBaseTerm;
import com.yuyou.tas.service.api.lesson.entity.BaseTrimester;
import com.yuyou.tas.util.bean.LoginRedisObj;
import com.yuyou.tas.util.bean.PageParams;
import com.yuyou.tas.util.bean.Pagination;
import com.yuyou.tas.util.bean.ResBoolSimpleInfo;
import com.yuyou.tas.util.bean.ReturnResult;
import com.yuyou.tas.util.config.SystemConfig;
import com.yuyou.tas.util.enums.OrganLimitEnums;

@Api(value="BaseTermController",description="学期操作接口")
@Validated
@RestController
@RequestMapping(value="/api/BaseTerm")
public class BaseTermController extends BaseController {

    @Autowired
    private IBaseTermService service;

    @Autowired
    private OrganLimitService organLimitService;


    @ApiOperation(value="添加学期")
    @RequestMapping(value="/addTerm",method = RequestMethod.POST)
    public ReturnResult addTerm(@Validated @ApiParam(value = "学期名称")@NotBlank(message = "学期名称不能为空")@RequestParam("name") String name,
                                @Validated @ApiParam(value = "序号")@NotNull(message = "序号不能为空")@RequestParam("sort") Integer sort,
                                  HttpServletRequest request){
        LoginRedisObj user = this.getUserObj(request);
        ResBoolSimpleInfo info = service.addTerm(name,sort, user.getIsSystem()? 1:0,null,
                                                user,user.getOrganizationId());
        return ReturnResult.returnRes(info.isSuccess() , info.getMessage() , null);
    }

    @ApiOperation(value="删除学期")
    @RequestMapping(value="/delTerm",method = RequestMethod.POST)
    public ReturnResult delTerm(@Validated @ApiParam(value = "学期ID")@NotNull(message = "学期ID不能为空")@RequestParam(value = "id") Long id,
                                HttpServletRequest request) throws Exception {
        LoginRedisObj user = this.getUserObj(request);
        if(!user.getIsSystem()) {
            organLimitService.checkOrganByOrganId(user.getOrganizationId(), id, OrganLimitEnums.type.base_trimester);
        }
        ResBoolSimpleInfo info = service.delTerm(id);
        return ReturnResult.returnRes(info.isSuccess() , info.getMessage() , null);
    }


    @ApiOperation(value="通过ID获取学期信息")
    @RequestMapping(value="/getBaseTerm",method = {RequestMethod.GET, RequestMethod.POST})
    public ReturnResult<BaseTrimester> getBaseTerm(@Validated @NotNull(message = "ID不能为空")@ApiParam(value = "ID" , required = true) @RequestParam(value = "id") Long id,
                                                   HttpServletRequest request) throws Exception {
        LoginRedisObj user = this.getUserObj(request);
        if(!user.getIsSystem()) {
            organLimitService.checkOrganByOrganId(user.getOrganizationId(), id, OrganLimitEnums.type.base_trimester);
        }
        ResBoolSimpleInfo info =  service.getTermByID(id);
        return ReturnResult.returnRes(info.isSuccess() , info.getMessage() , info.getData());
    }

    @ApiOperation(value="修改学期")
    @RequestMapping(value="/updateTerm",method = RequestMethod.POST)
    public ReturnResult updateTerm( @Validated @ApiParam(value = "ID")@NotNull(message = "ID不能为空")@RequestParam(value = "id") Long id,
                                    @Validated @NotBlank(message = "学期名称不能为空")@ApiParam(value = "学期名称")@RequestParam("name") String name,
                                    @Validated @NotNull(message = "序号 不能为空")@ApiParam(value = "序号")@RequestParam("sort") Integer sort,
                                    HttpServletRequest request) throws Exception {
        LoginRedisObj user = this.getUserObj(request);
        if(!user.getIsSystem()) {
            organLimitService.checkOrganByOrganId(user.getOrganizationId(), id, OrganLimitEnums.type.base_trimester);
        }
        ResBoolSimpleInfo info = service.updateTerm(name,sort, user.getIsSystem()? 1:0,null, id);
        return ReturnResult.returnRes(info.isSuccess() , info.getMessage() , null);
    }

    @ApiOperation(value = "查询学期")
    @RequestMapping(value = "/findBaseTermPage" ,method = {RequestMethod.GET,RequestMethod.POST})
    public ReturnResult<DtoBaseTerm> findBaseTermPage(HttpServletRequest request,
                                                       @Validated @ModelAttribute PageParams pageParams,
                                                       @ApiParam(value = "学期名称")@RequestParam(value = "name",required = false) String name,
                                                      @ApiParam(value = "是否过滤学期状态：1、不过滤，0或不传、过滤")@RequestParam(value = "isFilterUse",required = false) Integer isFilterUse,
                                                      @ApiParam(value = "是否通过授课班级获取：1、是，0或不传、否")@RequestParam(value = "tag",required = false) Integer tag,
                                                      @ApiParam(value = "获取系统数据：1、是，0或不传、否")@RequestParam(value = "getSys" , required = false)Integer getSys){
        Map<String, Object> conditions = new HashMap<>();
        Pagination<DtoBaseTerm> queryPgn = new Pagination<>();

        if(!StringUtils.isEmpty(name)){
            conditions.put("name", name.trim());
        }
        if(isFilterUse == null || isFilterUse == 0){
            conditions.put("isUse" , 1);
        }

        if(getSys != null && getSys == 1){//获取系统学期

            conditions.put("organ_id", SystemConfig.SYS_ORGAN_ID);//查询系统机构
            queryPgn.setConditions(conditions);
            queryPgn.setPageParams(pageParams);

            int total = service.findTermCount(queryPgn);
            queryPgn.setTotal(total);
            queryPgn.toBePage();
            if(total > 0){
                List<DtoBaseTerm> list = service.findTermPageList(queryPgn);
                queryPgn.setList(list);
            }
        }else{//获取机构学期
            LoginRedisObj user = this.getUserObj(request);
            conditions.put("organ_id", user.getOrganizationId());//默认查询个人所在机构的校区

            if(user.getIsManager() || tag == null || tag != 1){
                queryPgn.setConditions(conditions);
                queryPgn.setPageParams(pageParams);

                int total = service.findTermCount(queryPgn);
                queryPgn.setTotal(total);
                queryPgn.toBePage();
                if(total > 0){
                    List<DtoBaseTerm> list = service.findTermPageList(queryPgn);
                    queryPgn.setList(list);
                }

            }else{
                conditions.put("userId" , user.getUserId());
                queryPgn.setConditions(conditions);
                queryPgn.setPageParams(pageParams);

                int total = service.findUserTermCount(queryPgn);
                queryPgn.setTotal(total);
                queryPgn.toBePage();
                if(total > 0){
                    List<DtoBaseTerm> list = service.findUserTermPageList(queryPgn);
                    queryPgn.setList(list);
                }

            }
        }

        return ReturnResult.success(queryPgn);
    }



    @ApiOperation(value="修改学期启用状态")
    @RequestMapping(value="/updateTermStatus",method = RequestMethod.POST)
    public ReturnResult updateTermStatus( @Validated @ApiParam(value = "ID")@NotNull(message = "ID不能为空")@RequestParam(value = "id") Long id,
                                    @Validated @NotNull(message = "学期状态不能为空")@ApiParam(value = "学期状态：0、不启用，1、启用")@RequestParam("isUse") Integer isUse,
                                    HttpServletRequest request) throws Exception {
        LoginRedisObj user = this.getUserObj(request);
        if(!user.getIsSystem()) {
            organLimitService.checkOrganByOrganId(user.getOrganizationId(), id, OrganLimitEnums.type.base_trimester);
        }
        if(isUse == null || (isUse != 0 && isUse != 1)){
            return ReturnResult.returnRes(false , "isUse必须为0或1", null);
        }
        ResBoolSimpleInfo info = service.updateTermStatus(id , isUse);
        return ReturnResult.returnRes(info.isSuccess() , info.getMessage() , null);
    }


    @ApiOperation(value = "查询系统学期")
    @RequestMapping(value = "/findSysTermPage" ,method = {RequestMethod.GET,RequestMethod.POST})
    public ReturnResult<DtoBaseTerm> findSysTermPage(HttpServletRequest request,
                                                      @Validated @ModelAttribute PageParams pageParams,
                                                      @ApiParam(value = "学期名称")@RequestParam(value = "name",required = false) String name,
                                                      @ApiParam(value = "是否过滤学期状态：1、不过滤，0或不传、过滤")@RequestParam(value = "isFilterUse",required = false) Integer isFilterUse){
        Map<String, Object> conditions = new HashMap<>();
        Pagination<DtoBaseTerm> queryPgn = new Pagination<>();
//        LoginRedisObj user = this.getUserObj(request);

        /*if(user.getIsManager() || tag == null || tag != 1){*/
            if(!StringUtils.isEmpty(name)){
                conditions.put("name", name.trim());
            }
            if(isFilterUse == null || isFilterUse == 0){
                conditions.put("isUse" , 1);
            }

            conditions.put("organ_id", SystemConfig.SYS_ORGAN_ID);//查询系统机构
            queryPgn.setConditions(conditions);
            queryPgn.setPageParams(pageParams);

            int total = service.findTermCount(queryPgn);
            queryPgn.setTotal(total);
            queryPgn.toBePage();
            if(total > 0){
                List<DtoBaseTerm> list = service.findTermPageList(queryPgn);
                queryPgn.setList(list);
            }

        /*}else{
            if(!StringUtils.isEmpty(name)){
                conditions.put("name", name.trim());
            }
            if(isFilterUse == null || isFilterUse == 0){
                conditions.put("isUse" , 1);
            }
            conditions.put("userId" , user.getUserId());
            conditions.put("organ_id", user.getOrganizationId());//默认查询个人所在机构的校区
            queryPgn.setConditions(conditions);
            queryPgn.setPageParams(pageParams);

            int total = service.findUserTermCount(queryPgn);
            queryPgn.setTotal(total);
            queryPgn.toBePage();
            if(total > 0){
                List<DtoBaseTerm> list = service.findUserTermPageList(queryPgn);
                queryPgn.setList(list);
            }

        }*/

        return ReturnResult.success(queryPgn);
    }
}
